package frontend;

/*
 * Client UDP to send messages
 * to RM1, RM2, RM3, and ReplicaManager
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
//import java.nio.charset.Charset;
import java.util.concurrent.Callable;
import communication.Message;

public class Communicator implements Callable<Integer>{
	DatagramSocket clientUDPSocket = null;
	InetAddress address = null;
	int port = 0;
	byte[] sendMessage;
	byte[] receivedMessage;
	Message message;


	public Communicator (DatagramSocket socket,  String serverName, int portNo) throws UnknownHostException {
		clientUDPSocket = socket;
		address = InetAddress.getByName(serverName);
		sendMessage = new byte [32]; // client's message
		port = portNo; // server's port
		receivedMessage = new byte [32];
		System.out.println("Connecting to host " + serverName + " at "+ address + " and port "+port);
	}

	@Override
	public Integer call() throws IOException {
		try {			
			// send request
			DatagramPacket requestToServer = new DatagramPacket(sendMessage, sendMessage.length, address, port);
			clientUDPSocket.send(requestToServer);

			// receive reply
			DatagramPacket replyFromServer = new DatagramPacket(receivedMessage, receivedMessage.length);
			clientUDPSocket.receive(replyFromServer);

			message = new Message();
			return message.byteToInt(receivedMessage);

		}catch (SocketException e){
			System.out.println("Client Socket Exception: " + e.getMessage());
		}catch (IOException e){
			System.out.println("IOException: " + e.getMessage());
		}finally {
			if(clientUDPSocket != null) clientUDPSocket.close();
			System.out.println("Closed client socket in finally!");
		}
		System.out.println("Exiting try catch in client!");
		return null;
	}
	
}


